"""模拟数据生成器"""

import random
from datetime import datetime, timedelta
from typing import List, Optional

from ..schemas import ReportInfo, ReportType, ReportStatus, SpecialReportType


class MockDataGenerator:
    """模拟数据生成器"""

    # 医院列表
    HOSPITALS = [
        {"id": "001", "name": "山东省立医院"},
        {"id": "002", "name": "山东大学齐鲁医院"},
        {"id": "003", "name": "济南市中心医院"},
        {"id": "004", "name": "青岛市立医院"},
        {"id": "005", "name": "烟台毓璜顶医院"},
    ]

    # 医生列表
    DOCTORS = [
        "王春霞", "李明华", "张建国", "刘芳", "陈志强",
        "赵丽娜", "孙伟", "周敏", "吴强", "郑红"
    ]

    # 检验项目
    LABORATORY_ITEMS = [
        "血常规", "尿常规", "肝功能", "肾功能", "血脂四项",
        "血糖", "糖化血红蛋白", "乙肝五项", "丙肝抗体", "梅毒抗体",
        "HIV抗体", "甲状腺功能", "肿瘤标志物", "电解质", "凝血功能"
    ]

    # 检查项目
    EXAMINATION_ITEMS = [
        "CT", "MRI", "X光", "超声", "心电图",
        "脑电图", "胃镜", "肠镜", "支气管镜", "病理检查",
        "骨密度", "肺功能", "眼底照相", "听力测试", "视力检查"
    ]

    # 特殊报告类型
    SPECIAL_TYPES = [
        SpecialReportType.NUCLEIC_ACID_SINGLE,
        SpecialReportType.NUCLEIC_ACID_MIXED,
        SpecialReportType.MICROBIOLOGICAL_POSITIVE,
        SpecialReportType.MICROBIOLOGICAL_NEGATIVE,
        None  # 普通报告
    ]

    # 报告状态
    REPORT_STATUSES = [
        ReportStatus.REGISTERED,
        ReportStatus.CALLED,
        ReportStatus.CHECKED,
        ReportStatus.SUBMITTED,
        ReportStatus.REVIEWED,
        ReportStatus.RESCINDED,
        ReportStatus.CANCELLED,
        ReportStatus.REJECTED,
        ReportStatus.PASSED,
    ]

    @classmethod
    def generate_report_id(cls) -> str:
        """生成报告ID"""
        return f"RPT{random.randint(100000, 999999)}"

    @classmethod
    def generate_report_item(cls, report_type: ReportType) -> str:
        """生成报告项目"""
        if report_type == ReportType.LABORATORY:
            return random.choice(cls.LABORATORY_ITEMS)
        else:
            return random.choice(cls.EXAMINATION_ITEMS)

    @classmethod
    def generate_report_time(cls, start_time: str, end_time: str) -> str:
        """生成报告时间"""
        start_dt = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end_dt = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")

        # 在指定时间范围内随机生成
        time_diff = end_dt - start_dt
        random_seconds = random.randint(0, int(time_diff.total_seconds()))
        report_time = start_dt + timedelta(seconds=random_seconds)

        return report_time.strftime("%Y-%m-%d %H:%M:%S")

    @classmethod
    def generate_pdf_url(cls, report_id: str) -> Optional[str]:
        """生成PDF链接"""
        if random.random() > 0.3:  # 70%的概率有PDF
            return f"https://example.com/reports/{report_id}.pdf"
        return None

    @classmethod
    def generate_reports(
        cls,
        patient_name: str,
        start_time: str,
        end_time: str,
        hospital_ids: Optional[List[str]] = None,
        patient_type: Optional[str] = None,
        count: int = 5
    ) -> List[ReportInfo]:
        """生成报告列表"""
        reports = []

        # 如果没有指定医院ID，使用所有医院
        if not hospital_ids:
            hospital_ids = [h["id"] for h in cls.HOSPITALS]

        # 根据患者类型调整报告数量
        if patient_type == "2":  # 住院患者通常报告更多
            count = random.randint(8, 15)
        elif patient_type == "1":  # 门诊患者报告较少
            count = random.randint(2, 8)
        else:
            count = random.randint(3, 10)

        for _ in range(count):
            report_id = cls.generate_report_id()
            hospital_id = random.choice(hospital_ids)
            report_type = random.choice([ReportType.LABORATORY, ReportType.EXAMINATION])

            # 生成报告项目
            item = cls.generate_report_item(report_type)

            # 生成报告时间
            report_time = cls.generate_report_time(start_time, end_time)

            # 随机选择医生
            doctor = random.choice(cls.DOCTORS)

            # 随机选择特殊类型（10%概率）
            special_type = random.choice(cls.SPECIAL_TYPES) if random.random() < 0.1 else None

            # 随机选择报告状态
            status = random.choice(cls.REPORT_STATUSES)

            # 随机选择是否敏感报告（5%概率）
            is_empty = "1" if random.random() < 0.05 else "0"

            # 生成PDF链接
            pdf_url = cls.generate_pdf_url(report_id)

            report = ReportInfo(
                hospital_id=hospital_id,
                id=report_id,
                type=report_type,
                time=report_time,
                doctor=doctor,
                item=item,
                special_types=special_type,
                status=status,
                is_empty=is_empty,
                pdf_url=pdf_url
            )

            reports.append(report)

        # 按时间排序
        reports.sort(key=lambda x: x.time, reverse=True)

        return reports

    @classmethod
    def generate_empty_reports(cls) -> List[ReportInfo]:
        """生成空报告列表"""
        return []

    @classmethod
    def get_hospital_info(cls, hospital_id: str) -> Optional[dict]:
        """获取医院信息"""
        for hospital in cls.HOSPITALS:
            if hospital["id"] == hospital_id:
                return hospital
        return None


def generate_mock_reports(
    patient_name: str,
    start_time: str,
    end_time: str,
    hospital_ids: Optional[List[str]] = None,
    patient_type: Optional[str] = None,
    count: int = 5
) -> List[ReportInfo]:
    """生成模拟报告数据的便捷函数"""
    return MockDataGenerator.generate_reports(
        patient_name=patient_name,
        start_time=start_time,
        end_time=end_time,
        hospital_ids=hospital_ids,
        patient_type=patient_type,
        count=count
    )